/**
 * @author Timzhong <2164992949@qq.com>
 * 动态表格，横坐标为日期，纵坐标为数据，目前不需要输入数据，全部采用随机生成数据。
 */
import { Component, Input, OnDestroy, OnInit, OnChanges } from '@angular/core';
import { ChartTheme, DynamicLineChartConfig } from '../chart-option';

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit, OnDestroy, OnChanges {
  @Input() chartTheme: ChartTheme = {};
  @Input() dynamicLineChartConfig: DynamicLineChartConfig = {
    step: 1,
    interval: 1000,
    startDate: new Date(2019, 9, 1),
    initValue: 100
  };
  @Input() flush: number = 1; // 为更新图标使用，适配 OnChanges，无实际用途

  options: any;
  updateOptions: any;

  private oneDay = 24 * 3600 * 1000;
  private now: Date;
  private value: number;
  private data: any[];
  private timer: any;
  private step: number;
  private interval: number;
  private initValue: number;
  constructor() {}

  ngOnInit(): void {
    // generate some random testing data:
    this.data = [];
    this.now = this.dynamicLineChartConfig.startDate || new Date(2000, 9, 1);
    this.initValue = this.dynamicLineChartConfig.initValue || 100;
    this.value = Math.random() * this.initValue;
    this.step = this.dynamicLineChartConfig.step || 1;
    this.interval = this.dynamicLineChartConfig.interval || 1000;

    for (let i = 0; i < 100; i++) {
      this.data.push(this.randomData());
    }

    // initialize chart options:
    this.options = {
      color: [this.chartTheme.color || '#3398DB'],
      title: {
        text: this.chartTheme.title || null,
        show: this.chartTheme.title ? true : false
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          params = params[0];
          const date = new Date(params.name);
          return (
            date.getDate() +
            '/' +
            (date.getMonth() + 1) +
            '/' +
            date.getFullYear() +
            ' : ' +
            params.value[1]
          );
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
        splitLine: { show: true }
      },
      series: [
        {
          name: 'Mocking Data',
          type: 'line',
          showSymbol: false,
          hoverAnimation: false,
          data: this.data
        }
      ]
    };

    // 暂时不需要动态的图表所以注释了，如果需要模拟动态数据，取消注释
    // Mock dynamic data:
    // this.timer = setInterval(() => {
    //   for (let i = 0; i < this.step; i++) {
    //     this.data.shift();
    //     this.data.push(this.randomData());
    //   }

    //   // update series data:
    //   this.updateOptions = {
    //     series: [
    //       {
    //         data: this.data
    //       }
    //     ]
    //   };
    // }, this.interval);
  }

  ngOnChanges(): void {
    // generate some random testing data:
    this.data = [];
    this.now = this.dynamicLineChartConfig.startDate || new Date(2000, 9, 1);
    this.initValue = this.dynamicLineChartConfig.initValue || 100;
    this.value = Math.random() * this.initValue;
    this.step = this.dynamicLineChartConfig.step || 1;
    this.interval = this.dynamicLineChartConfig.interval || 1000;

    for (let i = 0; i < 100; i++) {
      this.data.push(this.randomData());
    }

    // initialize chart options:
    this.options = {
      color: [this.chartTheme.color || '#3398DB'],
      title: {
        text: this.chartTheme.title || null,
        show: this.chartTheme.title ? true : false
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          params = params[0];
          const date = new Date(params.name);
          return (
            date.getDate() +
            '/' +
            (date.getMonth() + 1) +
            '/' +
            date.getFullYear() +
            ' : ' +
            params.value[1]
          );
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
        splitLine: { show: true }
      },
      series: [
        {
          name: 'Mocking Data',
          type: 'line',
          showSymbol: false,
          hoverAnimation: false,
          data: this.data
        }
      ]
    };

    // 暂时不需要动态的图表所以注释了，如果需要模拟动态数据，取消注释
    // Mock dynamic data:
    // this.timer = setInterval(() => {
    //   for (let i = 0; i < this.step; i++) {
    //     this.data.shift();
    //     this.data.push(this.randomData());
    //   }

    //   // update series data:
    //   this.updateOptions = {
    //     series: [
    //       {
    //         data: this.data
    //       }
    //     ]
    //   };
    // }, this.interval);
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }

  randomData() {
    if (Math.random() > 0.48) {
      // 小于0.5数据总体增长
      this.value += this.initValue * Math.random() * 10;
    } else {
      this.value -= this.initValue * Math.random() * 10; // 随机割9菜，制造数据波动
    }
    this.now = new Date(this.now.getTime() + this.oneDay);
    this.value += Math.random() * 20 - 10;
    this.value = this.value > 0 ? this.value : 0;
    return {
      name: this.now.toString(),
      value: [
        [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
        Math.round(this.value)
      ]
    };
  }
}
